<!--
author:        hejy <silentmanager@163.com>
date:          2024-11-01 00:29:38
component:     index
Copyright © YourCompanyName All rights reserved
普通客户
-->

<template>
  <div>
    <FormComponent ref="formRef" :config="formConfig">
      <template #submit>
        <div style="margin-left: 24px">
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />重置</el-button>
          <el-button
            v-hasPermi="['crm:customer:distribute']"
            type="warning"
            @click="handledTransfer"
            >转派</el-button
          >
        </div>
      </template>
    </FormComponent>

    <!-- 表格 -->
    <el-card style="margin-top: 24px">
      <el-alert :title="'已选择 ' + selectedCount + ' 项'" type="success" />
      <el-table
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        :data="list"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="name" />
        <el-table-column label="客户手机号" prop="mobile">
          <template #default="{ row }">
            <span>{{ formatPhoneNumber(row.mobile) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" prop="detailAddress" />
        <el-table-column label="客户类型" prop="level" />
        <el-table-column label="性别" prop="sex" />
        <el-table-column label="沉默天数" prop="silenceDay" />
        <el-table-column label="订单数" prop="orderQuantity" />
        <el-table-column label="订单金额" prop="orderAmount" />
        <el-table-column label="分配人" prop="ownerUserName" />
        <el-table-column label="分配时间" prop="ownerTime" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <div style="display: flex">
              <el-button
                link
                type="primary"
                v-hasPermi="['bms:order-info:re-order']"
                @click="handlePlaceOrder(scope.row)"
                >下单</el-button
              >
              <el-button
                link
                v-hasPermi="['crm:customer:query']"
                type="primary"
                @click="viewDetails(scope.row)"
                >详情</el-button
              >
              <el-button
                link
                type="primary"
                v-hasPermi="['crm:customer:update']"
                @click="handleEmit(scope.row)"
                >编辑</el-button
              >
              <el-button
                link
                type="primary"
                v-hasPermi="['crm:customer:remark:create']"
                @click="showRemarkDialog(scope.row)"
                >备注</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 备注弹窗 -->
    <Remark :remarkId="remarkId" @success="getList" v-model:visible="isRemarkDialogVisible" />
    <!-- 客户详情抽屉 -->
    <CustomerDetailDrawer
      v-model="isDetailDrawerVisible"
      :detailItem="detailItem"
      @success="getList"
      :get-wine="true"
    />
    <!-- 编辑弹窗 -->
    <Emit v-model:visible="emitVisible" :emitData="emitData" @success="getList" />
    <!-- 转派弹窗 -->
    <Transfer v-model:visible="isTransferDialogVisible" :ids="selectId" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import FormComponent from '@/components/FormComponent/index.vue'
import Remark from '@/views/customer/wait-developed/components/remark.vue'
import CustomerDetailDrawer from '@/views/customer/wait-developed/components/detail.vue'
import Emit from '@/views/customer/wait-developed/components/emit.vue'
import { CustomerEmitReq, pageCustomerUser } from '@/api/customer'
import Transfer from './components/transfer.vue'
import { repurchasePage } from '@/api/return-purchase'
import { useDeptList } from '@/hooks/useDeptList'
import { defaultProps } from '@/utils/tree'
import { lockStatus, simpleListUser } from '@/api/order/create'
import { defaultTime, formatPhoneNumber } from '@/utils'
import router from '@/router'

const message = useMessage()
const { deptList } = useDeptList()
// ----------------------------- 下单 -----------------------------
const handlePlaceOrder = async (row) => {
  try {
    const isLock = await lockStatus(row.mobile)
    const data = {
      customerPhone: row.mobile,
      customerName: row.name,
      address: row.detailAddress,
      customerType: row.level,
      gender: row.sex,
      age: row.age,
      lock: isLock.data
    }
    router.push({
      name: 'Creation',
      state: { data }
    })
  } catch (e) {
    console.error(e)
  }
}
// ----------------------------- 转派弹窗状态 -----------------------------
const isTransferDialogVisible = ref<boolean>(false) // 定义对话框可见性的状态
const handledTransfer = () => {
  if (selectedCount.value === 0) {
    message.warning('请至少选择一个客户')
    return
  }
  isTransferDialogVisible.value = true
}
// ----------------------------- 编辑弹窗状态 -----------------------------
const emitData = ref<CustomerEmitReq>()
const emitVisible = ref<boolean>(false) // 定义对话框可见性的状态
// 显示弹窗的处理函数
const handleEmit = (row) => {
  emitData.value = {
    id: row.id,
    name: row.name,
    detailAddress: row.detailAddress,
    sex: row.sex
  }
  emitVisible.value = true
}
// ----------------------------- 备注弹窗状态 -----------------------------
const remarkId = ref(0)
const isRemarkDialogVisible = ref<boolean>(false) // 定义对话框可见性的状态
// 显示弹窗的处理函数
const showRemarkDialog = (row) => {
  remarkId.value = row.id
  isRemarkDialogVisible.value = true
}
// ----------------------------- 详情抽屉状态 -----------------------------
const isDetailDrawerVisible = ref(false)
const detailItem = ref<pageCustomerUser>()
const viewDetails = (row) => {
  detailItem.value = row
  isDetailDrawerVisible.value = true // 打开详情抽屉
}

// --------------------  表格  ---------------------
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})
const selectId = ref<number[]>([])
const selectedCount = ref(0)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const [silenceDayStart, silenceDayEnd] = formRef.value?.formData.silenceDay || []
    const [orderTimeStart, orderTimeEnd] = formRef.value?.formData.orderTime || []
    const [allocateTimeStart, allocateTimeEnd] = formRef.value?.formData.allocateTime || []
    const [recyclingTimeStart, recyclingTimeEnd] = formRef.value?.formData.recyclingTime || []
    const data = await repurchasePage({
      ...queryParams,
      ...formRef.value?.formData,
      repurchaseLevel: '0',
      silenceDayStart,
      silenceDayEnd,
      orderTimeStart,
      orderTimeEnd,
      allocateTimeStart,
      allocateTimeEnd,
      recyclingTimeStart,
      recyclingTimeEnd
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}
// 处理选择变化的函数
const handleSelectionChange = (selection: any[]) => {
  selectId.value = selection.map((item) => item.id)
  selectedCount.value = selection.length // 更新选中项的数量
}

const getRowKey = (row: any) => {
  return row.id
}

/** 初始化 */
onMounted(() => {
  getList()
})
// ==================== 表单  ====================
const formRef = ref<InstanceType<typeof FormComponent>>()
const allocationList = ref<{ label: string; value: number }[]>([])
const inputList = ref<{ label: string; value: number }[]>([])
const dockingList = ref<{ label: string; value: number }[]>([])
const simpleListUserFn = async (deptId: string, type: 'allocation' | 'input' | 'docking') => {
  try {
    if (!deptId) {
      return
    }
    const res = await simpleListUser({ deptId })
    const data = res.map((item) => {
      return {
        label: item.nickname,
        value: item.id
      }
    })
    if (type === 'allocation') {
      allocationList.value = data
    }
    if (type === 'input') {
      inputList.value = data
    }
    if (type === 'docking') {
      dockingList.value = data
    }
  } catch (e) {
    console.error(e)
  }
}
watch(
  [() => formRef.value?.formData.allocateDept],
  ([newTeam]) => {
    formRef.value?.setSingleData('allocateUser', '')
    simpleListUserFn(newTeam, 'allocation')
  },
  { deep: true }
)
watch(
  [() => formRef.value?.formData.creatorDept],
  ([newTeam]) => {
    formRef.value?.setSingleData('creator', '')
    simpleListUserFn(newTeam, 'input')
  },
  { deep: true }
)
watch(
  [() => formRef.value?.formData.contactDept],
  ([newTeam]) => {
    formRef.value?.setSingleData('contactUser', '')
    simpleListUserFn(newTeam, 'docking')
  },
  { deep: true }
)
const formConfig = ref([
  {
    label: '分配人',
    prop: 'allocateDept',
    type: 'tree',
    options: {
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true,
      placeholder: '请选择分配组织'
    }
  },
  {
    label: '',
    prop: 'allocateUser',
    type: 'select',
    options: {
      placeholder: '请选择分配人',
      style: 'width: 240px',
      options: allocationList
    }
  },
  {
    label: '录入人',
    prop: 'creatorDept',
    type: 'tree',
    options: {
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true,
      placeholder: '请选择录入组织'
    }
  },
  {
    label: '',
    prop: 'creator',
    type: 'select',
    options: {
      placeholder: '请选择录入人',
      style: 'width: 240px',
      options: inputList
    }
  },
  {
    label: '对接人',
    prop: 'contactDept',
    type: 'tree',
    options: {
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true,
      placeholder: '请选择对接组织'
    }
  },
  {
    label: '',
    prop: 'contactUser',
    type: 'select',
    options: {
      placeholder: '请选择对接人',
      style: 'width: 240px',
      options: dockingList
    }
  },
  {
    label: '客户手机',
    prop: 'mobile',
    type: 'input',
    options: { placeholder: '请输入客户手机' }
  },
  {
    label: '订单号',
    prop: 'orderNo',
    type: 'input',
    options: { placeholder: '请输入订单号' }
  },
  {
    label: '快递单号',
    prop: 'trackNo',
    type: 'input',
    options: { placeholder: '请输入快递单号' }
  },
  {
    label: '商品名称',
    prop: 'goodsName',
    type: 'input',
    options: { placeholder: '请输入商品名称' }
  },
  {
    label: '订单总金额',
    prop: 'orderAmountStart',
    type: 'number',
    options: { placeholder: '金额下限', precision: '2', min: '0' }
  },
  {
    label: '',
    prop: 'orderAmountEnd',
    type: 'number',
    options: { placeholder: '金额上限', precision: '2', min: '0' }
  },
  {
    label: '沉默天数',
    prop: 'silenceDay',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  },
  {
    label: '所属组织',
    prop: 'deptId',
    type: 'tree',
    options: {
      placeholder: '请选择所属组织',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '下单时间',
    prop: 'orderTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  },
  {
    label: '分配时间',
    prop: 'allocateTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  },
  {
    label: '回收时间',
    prop: 'recyclingTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  }
])
</script>
